var app = getApp();
var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var MPage = require('../MPage.js');
var cInfoSearch = require('../../components/cInfoSearch/cInfoSearch.js');
Page(common.extendPage(MPage, {
    data: {
        currentTab: 0,
        bannerList: [],
        bannerListLayout: [],
        homeCatSetting: [],
        noteList: [],
        page: 1,
        scrollTop: 0,
        loading: false,
        moreLoading: false,
        noMore: false,
        zDList: [],
        isHomePage: true,
        tabshow: true
    },

    onLoad: function(options) {
        var _self = this;
        this.options = options;
        cInfoSearch.init({
            page: _self
        });
        this._init();
    },

    onShow() {
        var _self = this;
        this.setData({
            isLogin: !!app.getUserSid(),
        });
        this._getUserLoc();
    },
    onShareAppMessage: function() {
        return {
            title: app.getShop()['shareTitle'],
            path: '/pages/cityInfoIndex/cityInfoIndex',
        }
    },
    onPullDownRefresh() {
        this._init();
    },
    onReachBottom: function() {
        this._loadMore();
    },
    /**
     * 页面初始化
     */
    _init() {
        var _self = this;
        common.initApp({
            extSuc: function() {
                var dataObj = {
                    winHei: app.getWinHei(),
                    winWid: app.getWinWid()
                };
                //异步并行执行，统一处理结果        
                util.async([
                    //获取页面数据
                    function(next) {
                        _self.getIndexData(function(res) {
                            var {
                                bannerList,
                                homeCatSetting,
                                xcx_website_contact,
                                shouldCheckComment
                            } = res.result;

                            Object.assign(dataObj, {
                                bannerList,
                                homeCatSetting
                            });

                            if (xcx_website_contact) {
                                app.setShopTel(xcx_website_contact);
                            }
                            if (shouldCheckComment) {
                                app.setCheckComment(shouldCheckComment);
                            }
                            next();
                        });
                    }
                ], function() {
                    _self.setData(dataObj);
                    wx.stopPullDownRefresh();
                });

                util.jumpByScene(_self.options.scene);
            },
            loginSuc: function() {
                _self.setData({
                    isLogin: !!app.getUserSid()
                });

                _self.$loginSuc();
                _self._toTab(0, function() {
                    _self._getZDList(function() {
                        _self.setData({
                            dataLoaded: true
                        });
                    });

                });
            }
        });
    },
    /**
     * 获取首页数据
     */
    getIndexData: function(cb) {
        ajax.P('/openapi/CInformation/index', {}, cb);
    },
    /**
     * 页面跳转
     */
    _jump: function(evt) {
        common.jump(evt);
    },
    /**
     * 获取地理位置
     */
    _getUserLoc: function() {
        wx.getLocation({
            type: 'wgs84', //返回可以用于wx.openLocation的经纬度
            success: function(res) {
                var latitude = res.latitude;
                var longitude = res.longitude;
                app.setLng(longitude);
                app.setLat(latitude);
            }
        })
    },
    /**
     * 事件切换tab
     */
    _tabSwitch: function(evt) {
        var index = +evt.currentTarget.dataset.current || 0;
        var formId = evt.detail.formId;
        var _self = this;
        wx.getSetting({
            success: (res) => {
                if (index == 1) {
                    if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                        util.alert('需要获取您的地理位置，请确认授权', function() {
                            wx.openSetting({
                                success: (res) => {
                                    _self._getUserLoc();
                                    /*
                                     * res.authSetting = {
                                     *   "scope.userInfo": true,
                                     *   "scope.userLocation": true
                                     * }
                                     */
                                }
                            })
                        })
                        return false;
                    }
                }

                this._toTab(index);
            }
        })
        common.submitForm(formId);
    },

    _toTab: function(index, cb) {
        this.setData({
            currentTab: index,
            page: 1,
            noMore: false,
        });
        this._getNoteList({ ty: index }, cb, true);
    },
    /**
     * 获取信息列表
     */
    _getNoteList: function(params, cb, isReset) {
        var self = this;
        var ty = params.ty;
        var isMore = params.isMore;
        var page = self.data.page || 1;
        var url = '';
        var lng = app.getLng();
        var lat = app.getLat();

        switch (ty) {
            case 0:
                url = '/openapi/CInformation/noteListOrderByTime';
                break;
            case 1:
                url = '/openapi/CInformation/noteListOrderByAddress';
                break;
        }

        if (isMore) {
            self.setData({
                moreLoading: true
            });
        } else {
            self.setData({
                loading: true
            });
        }
        ajax.G(url, {
            page: page,
            lng: lng || '',
            lat: lat || ''
        }, function(data) {
            var list = data.result.noteList || [];

            list.forEach(function(item) {
                if (item.zan_num && item.zan_num.length > 4) {
                    item.zan_num = parseInt(item.zan_num / 10000) + '万+';
                }
                if (item.page_view && item.page_view.length > 4) {
                    item.page_view = parseInt(item.page_view / 10000) + '万+';
                }
            })

            var noteList = self.data.noteList;

            if (isReset) {
                noteList = [];
            }
            var toData = {
                noteList: noteList.concat(list),
                noMore: list.length == 0,
                page: self.data.page + 1,
            };
            toData[isMore ? 'moreLoading' : 'loading'] = false;
            self.setData(toData);
            cb && cb();
        });
    },

    /**
     * 加载更多
     */
    _loadMore: function() {
        if (this.data.moreLoading || this.data.loading || this.data.noMore) {
            return;
        }
        this._getNoteList({
            ty: this.data.currentTab,
            isMore: true
        });
    },
    /**
     * 页面滚动
     */
    _scroll: function(evt) {
        var scrollTop = evt.detail.scrollTop;
        this.setData({
            scrollTop
        })
    },
    /**
     * 调用电话功能
     */
    _calling: function(evt) {
        var phoneNumber = evt.currentTarget.dataset.phoneNumber;
        wx.makePhoneCall({
            phoneNumber: phoneNumber,
            success: function() {},
            fail: function() {}
        })
    },
    /**
     * 获取置顶的列表
     */
    _getZDList: function(cb) {
        var _self = this;
        var url = '/openapi/CInformation/topStickNoteList';
        ajax.P(url, {}, function(data) {
            _self.setData({
                zDList: data.result.list
            })
            cb && cb();
        })
    }
}))